const mysql = require('mysql');
const config = require('../config/database');
// 使用连接池
const pool = mysql.createPool(config.mysql);

/**
 * 对query执行的结果自定义返回JSON结果
 */
function responseDoReturn(res, result, resultJSON) {
  console.log(result)
  if (typeof result === 'undefined') {
    res.json({
      code: '201',
      msg: 'failed to do'
    });
  } else {
    res.json({
      code:1,
      result:result
    });
  }
};

/**
 * 封装query之sql带不占位符func
 */
function query(sql, callback) {
  pool.getConnection(function (err, connection) {
    connection.query(sql, function (err, rows) {
      callback(err, rows);
      //释放链接
      connection.release();
    });
  });
}

/**
 * 封装query之sql带占位符func
 */
function queryArgs(sql, args, callback) {
  pool.getConnection(function (err, connection) {
    connection.query(sql, args, function (err, rows) {
      callback(err, rows);
      //释放链接
      connection.release();
    });
  });
}

function queryall(sql,args){
  return new Promise((resolve,reject) => {
    pool.getConnection((err,connection) => {
      if(err){
        reject(err);
        connection.release();
        return 
      }
      connection.query(sql,args,(err,rows) =>{
        if(err){
          reject(err);
          return 
        }
        resolve(rows)
        connection.release()
      })
    })
  })
}
//exports
module.exports = {
  query: query,
  queryArgs: queryArgs,
  doReturn: responseDoReturn,
  queryall:queryall,
  pool:pool
}